package com.tarena.rocketmq.study.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    //localhost:8080/send?msg=哈哈
    @GetMapping("/send")
    public String send(String msg){
        if (StringUtils.isEmpty(msg)){
            return "msg is null";
        }
        Message<String> message = MessageBuilder.withPayload(msg).build();
        //1.同步发送: 发送消息的生产者,必须等待rocketmq消息队列反馈 才继续执行代码
        //1.1 普通消息
        SendResult sendResult = rocketMQTemplate.syncSend(
                "test-01-topic",
                message);
        System.out.println(sendResult.getSendStatus());
        //1.2 延迟消息 send方法多了2个参数 timeout delayLevel
        //timeout表示发送链接超时时间 网络通常可以定义超时时间较短,如果波动常见 可以定义稍长的时间
        /*SendResult sendResult = rocketMQTemplate.syncSend(
                "test-01-topic",
                message,500,4);
        System.out.println(sendResult.getSendStatus());*/
        //2.异步发送: 发送消息的生产者,发完消息 线程立刻向下执行代码. 通过回调获取反馈结果
        //2.1 异步普通消息
        //2.2 异步延迟消息
        //构造一个消息,可以在消息中携带任意类型的消息体数据 springboot整合对象会进行自动序列化
        /*//异步发送参数 destination 目标 message消息对象 SendCallback异步方法回调
        rocketMQTemplate.asyncSend("test-01-topic", message, new SendCallback() {
            //异步调用 接收rocketmq反馈
            //发送成功 调用onSuccess
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }
            //发送失败 调用onException
            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });*/
        return "success";
    }
}
